package com.yuexunit.mobilenurse.module.Login.presenter.impl;

import com.alibaba.fastjson.JSON;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Login.bean.SystemConfig;
import com.yuexunit.mobilenurse.module.Login.bean.YXLoginData;
import com.yuexunit.mobilenurse.module.Login.model.ILoginModel;
import com.yuexunit.mobilenurse.module.Login.presenter.IUserPresenter;
import com.yuexunit.mobilenurse.module.Login.ui.view.IUserView;
import com.yuexunit.mobilenurse.util.ProUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.StringUtils;
import org.slf4j.Logger;

import java.net.UnknownHostException;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by sslcjy on 16/1/20.
 */
public class UserPresenter implements IUserPresenter {

    private IUserView view;
    private ILoginModel model;
    public CompositeSubscription compositeSubscription = new CompositeSubscription();

    //记录Log
    private final Logger log = ProUtil.getLogger(UserPresenter.class);

    public UserPresenter(IUserView view, ILoginModel model) {
        this.view = view;
        this.model = model;
    }

    @Override
    public void getListParams() {

        compositeSubscription.add(
                model.getListParams()
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Subscriber<SystemConfig>() {
                            @Override
                            public void onCompleted() {
                                log.info("getListParams_onCompleted");
                            }

                            @Override
                            public void onError(Throwable e) {
                                log.error("getListParams_onError:" + e);
                                e.printStackTrace();
                            }

                            @Override
                            public void onNext(SystemConfig systemconfig) {
                                log.info("getListParams_onNext:"+systemconfig.toString());
                                view.saveSystemListParams(systemconfig);
                            }
                        }));

    }

    @Override
    public void doInLogin(String uid, String pwd) {
        if (!inputCheck(uid, pwd)) {
            return;
        }

        compositeSubscription.add(
                model.doInLogin(uid, pwd)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                log.info("UserPresenter_doInLogin_SHOW_DIALOG");
                                view.loadingDialogStatus(AppConfig.SHOW_DIALOG);
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .filter(new Func1<Object, Boolean>() {
                            @Override
                            public Boolean call(Object response) {
                                log.info("UserPresenter_doInLogin_response:"+response);
                                return response != null;
                            }
                        })
                        .filter(new Func1<Object, Boolean>() {
                            @Override
                            public Boolean call(Object response) {

                                JSONObject all, body;
                                String result = null;
                                try {
                                    all = new JSONObject(response.toString());
                                    body = all.getJSONObject("body");
                                    result = body.getString("response");

                                    log.info("UserPresenter_doInLogin_response:"+response.toString());
                                } catch (JSONException e) {
                                    log.error("UserPresenter_doInLogin_e:", e.toString());
                                }

                                if("null".equals(result)){
                                    view.loadingToastStatus("登录失败，请检验账号和密码...");
                                }
                                return !("null".equals(result));
                            }
                        })
                        .map(new Func1<Object, YXLoginData>() {
                            @Override
                            public YXLoginData call(Object response) {
                                YXLoginData Total = JSON.parseObject(response.toString(), YXLoginData.class);
                                YXLoginData loginData = Total.getBody();
                                log.info("UserPresenter_doInLogin:"+loginData.toString());
                                return loginData;
                            }
                        })
                        .filter(new Func1<YXLoginData, Boolean>() {
                            @Override
                            public Boolean call(YXLoginData yxLoginData) {
                                return "0".equals(yxLoginData.getHead().getRet_code());
                            }
                        })
                        .subscribe(new Subscriber<YXLoginData>() {
                            @Override
                            public void onCompleted() {
                                log.info("UserPresenter_doInLogin_onCompleted");
                                view.loadingDialogStatus(AppConfig.DISMISS_DIALOG);
                            }

                            @Override
                            public void onError(Throwable e) {
                                log.info("UserPresenter_doInLogin_onError:"+e);
                                view.loadingDialogStatus(AppConfig.DISMISS_DIALOG);
                                if (e instanceof UnknownHostException) {
                                    ViewInject.toast("网络连接失败...");
                                } else {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onNext(YXLoginData yxLoginData) {
                                log.info("UserPresenter_doInLogin_onNext:"+yxLoginData.toString());
                                view.doInLogin(yxLoginData);
                            }
                        }));
    }

    //检验账号密码输入格式是否有效
    public boolean inputCheck(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            ViewInject.toast("请输入有效账号");
            return false;
        }

        if (StringUtils.isEmpty(password)) {
            ViewInject.toast("请输入有效密码");
            return false;
        }
        return true;
    }
}
